package com.gestocasa.view.dialogs.areas;

import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.InputMap;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.KeyStroke;

import com.gestocasa.model.Attribute;
import com.gestocasa.view.dialogs.DialogBase;

public class AttributeDialog extends DialogBase {

	private Attribute attribute;
	
	private JLabel name;
	private JLabel type;
	private JLabel order;
	private JLabel defaultValue;
	private JTextField nameEdit;
	private JComboBox typeList;
	private JTextField orderEdit;
	private JTextField defaultValueEdit;
	
	public AttributeDialog(JDialog parent, Attribute attribute) {
		super(parent, (attribute==null) ? "Crear atributo" : "Modificar atributo", true);
		setLocationRelativeTo(parent);
		setResizable(false);
		
		this.attribute = new Attribute(attribute);
	}
	
	protected void initComponents() {
		name = new JLabel("Nombre : ");
		type = new JLabel("Tipo : ");
		order = new JLabel("Orden : ");
		defaultValue = new JLabel("Valor predeterminado : ");
		nameEdit = new JTextField();
		orderEdit = new JTextField();
		defaultValueEdit = new JTextField();
		typeList = new JComboBox(Attribute.getTypes());
		
		if(attribute != null) {
			nameEdit.setText(attribute.getName());
			orderEdit.setText(String.valueOf(attribute.getOrder()));
			defaultValueEdit.setText(attribute.getDefaultValue());
			typeList.setSelectedItem(attribute.getType());
		}
	}

	protected JPanel makePanels() {
		GridLayout layout = new GridLayout(4, 2);
		layout.setHgap(5);
		layout.setVgap(5);
		
		JPanel mainPanel = new JPanel();
		mainPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
		mainPanel.setLayout(layout);
		mainPanel.add(name);
		mainPanel.add(nameEdit);
		mainPanel.add(type);
		mainPanel.add(typeList);
		mainPanel.add(order);
		mainPanel.add(orderEdit);
		mainPanel.add(defaultValue);
		mainPanel.add(defaultValueEdit);
		return mainPanel;
	}

	protected Dimension getDefaultSize() {
		return new Dimension(300, 180);
	}
	
	@Override
	protected void doOK() {
		attribute = new Attribute();
		attribute.setName(nameEdit.getText());
		attribute.setType((String)typeList.getSelectedItem());
		attribute.setDefaultValue(defaultValueEdit.getText());
		
		try {
			attribute.setOrder(Integer.parseInt(orderEdit.getText()));
		}
		catch(NumberFormatException e) {
			attribute.setOrder(0);
		}
		
		super.doOK();
	}
	
	@Override
	protected void onKeyEnter() {
		doOK();
	}
	
	public Attribute getAttribute() {
		return attribute;
	}
}
